import requests
from django.http import HttpResponse
from django.shortcuts import render
from rest_framework import status
from rest_framework.response import Response
from rest_framework.utils import json
from rest_framework.views import APIView
from rest_framework_jwt import settings
from rest_framework_jwt.settings import api_settings

from apps.users.models import User


class WeChatLoginView(APIView):
    def get(self, request):
        return Response("已登录")
    """登录逻辑"""

    def post(self, request):
        # 前端发送code到后端，获取openid
        code = request.data.get('code')
        # print(request.data)
        openid = request.data.get('openId') if 'openId' in request.data else None
        # 判断用户是否是第一次登录
        try:
            user = User.objects.get(openid=openid)
        # 创建新用户
        except Exception:
            username = request.data.get('nickName')
            avatar = request.data.get('avatarUrl')
            print(len(avatar))
            user = User.objects.create(username=username, avatar=avatar, openid=openid)
            user.set_password(openid)
        # 手动签发jwt
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        resp_data = {
            "user_id" : user.id,
            "username": user.username,
            "avatar": user.avatar,
            "token":token
        }
        return Response(resp_data)


# class UserInfoView(APIView):
#
#     def post(self, request):
#         # 获取openid，取出数据
#         print(request.data)
#         openid = request.data.get('openId') if 'openId' in request.data else None
#         # print(openid)
#         user = User.objects.get(openid=openid)
#         resp_data = {
#             "uid" : user.id,
#             "username": user.username,
#             "avatar": user.avatar,
#         }
#         return Response(resp_data)